var App = {
	//url : 'http://200.98.140.15/avaliemais/api/request.php',
	url : 'http://localhost/avaliemais/api/request.php',
	imgs: 'http://200.98.140.15/avaliemais/api/pratos/',
	voting : function(id, points){
		$('.modal .voting[data-id="'+id+'"]').children('.star').each(function(i, elem){
			$(elem).removeClass('active');
		});

		for(i = 0;i < points;i++){
			$('.modal .voting[data-id="'+id+'"]').children('.star').eq(i).addClass('active');
		}		
	},
	rate : function(){
		App.Restaurantes.getList();
		$.each(App.Restaurantes.list, function (i,v){ 
			pontos 	= parseInt(v.points);
			var html = '<div class="voting" data-id="'+v.idrestaurantes+'">';
			html 	+= v.nome + '<br />';
			for(s = 0;s < 5;s++){
				if(s < pontos){
					html += '<div data-value="'+(s+1)+'" class="icon star active">&nbsp;</div>';
				}else{
					html += '<div data-value="'+(s+1)+'" class="icon star">&nbsp;</div>';
				}
			}
			html += '</div>';
			$('header .rating').append(html);
		});
		$(document.body).delegate('.top .icon.star, .modal icon.star', 'click', function(){
			App.voting($(this).parent().data('id'), $(this).data('value'));
		});
	},
	week : function(valor){
		var dias = ['Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'];
		return dias[valor];
	},
	Home : {
		init : function(){
			App.Home.options();
			App.Home.events();	
			if(App.Usuarios.client == null){
				App.Home.login();	
			}		
		},	
		login : function(){
			$('.modal').css({height: '20%'});
			$('.modal button').css({margin: '10px auto', display: 'block'});
			$('.modal, .mask').fadeIn();
			$('body').on('click', '#enviar', function(){
				App.Usuarios.auth();
			});
		},
		events : function(){
			$('.btn-restaurante').change(function(){
				sessionStorage.setItem('idrestaurante', $(this).data('idrestaurante') );
				sessionStorage.setItem('restaurante', $(this).data('restaurante') );
				sessionStorage.setItem('dia', $(this).val() );
				sessionStorage.setItem('page', 'Cardapio');
				window.location = 'cardapio.html';
			});
		},
		options : function(){			
			$.each(App.Restaurantes.list, function (i,v){
				html  = '<select class="btn-restaurante" data-idrestaurante="'+v.idrestaurantes+'" data-restaurante="'+v.nome+'" >';
					html += '<option>'+v.nome+'</option>';
					for(i = 0;i < 6;i++){
						html += '<option value="'+i+'">'+App.week(i)+'</option>';
					}
				html += '</select>';
				$('.container h1').after(html);
			}); 
		}
	},
	Avaliacoes : {
		list: null,
		response: null,
		getList : function(idpratos){
			$.ajax({
                type: 'POST',
                url: App.url ,
                data: { acao: 'listar', pagina: 'avaliacoes', parametros: idpratos},
                success: function(response){
                	App.Avaliacoes.list = response;
                },
                dataType: 'json',
                async: false
            });
		},
		appendList : function(idpratos){
			App.Avaliacoes.getList(idpratos);
			if(App.Avaliacoes.list.length > 0){
				$('.container').append('<br clear="all" /><h1>Avaliação e comentários</h1>');
				$.each(App.Avaliacoes.list, function (i,v){
					data = new Date(v.timestamp + ' 00:00:01');
					var html  = '<div class="comment">';
						html += '<h3>';
							html += '<div class="name">@'+v.login+' '+ data.toLocaleString().substring(0,10) +'&nbsp;&nbsp;</div>';
							for(s = 0;s < 5;s++){
								if(s < v.valor){
									html += '<div class="icon star small active">&nbsp;</div>';
								}else{
									html += '<div class="icon star small">&nbsp;</div>';
								}
							}
						html += '</h3>';
						html += '<p>'+v.descricao+'</p>';
					html += '</div>';

					$('.container').append(html);
				});
			}			
		},
		modal : function(){
			$('body').on('click', '#avaliar', function(){
		  		$('.mask').fadeIn();
		  		$('.modal .vote').remove();

		  		var idpratos = $(this).data('idpratos');
				var html = '<div class="voting" data-id="'+idpratos+'">';				
				for(s = 0;s < 5;s++){						
					html += '<div data-value="'+(s+1)+'" class="icon star">&nbsp;</div>';					
				}
				html += '</div>';
				$('.modal textarea').before('<div class="vote">De sua nota: '+html+'<br /></div>');				
				
				$(document.body).delegate('.icon.star', 'click', function(){
					App.voting(idpratos, $(this).data('value'));					
				});
		  		$('.modal').fadeIn();
			});
			$('body').on('click', '#cancelar', function(){
				$('.modal, .mask').fadeOut();
			});
			$('body').on('click', '#enviar', function(){
				App.Avaliacoes.assess();
				$('.modal, .mask').fadeOut();
			});
			sessionStorage.getItem('chave') != '' ? $('.password').val(sessionStorage.getItem('chave')) : '';
		},
		assess: function(){			
			$.ajax({
                type: 'POST',
                url: App.url ,
                data: { acao: 'insert', pagina: 'avaliacoes', descricao: $('textarea').val(), usuarios_idusuarios: App.Usuarios.client.idusuarios, pratos_idpratos: $('.voting').data('id'), valor: $('.modal .star.active').length  },
                success: function(response){
                	if(response != ''){
                		App.Avaliacoes.response = response;	
                	}	                							
                },
                async: false
            });
            /*
            if(App.Avaliacoes.response == null){
				window.plugins.toast.showShortBottom('Comentário inserido com sucesso, obrigado.');
				navigator.notification.vibrate(100);	
			}else{
				window.plugins.toast.showShortBottom('Você já avaliou hoje este prato.');
				navigator.notification.vibrate(100);
			}
			*/			
			$('.modal, .mask').fadeOut();			
			setTimeout("window.location.reload();", 1500);			
		}
	},
	Cardapio : {
		list: null,
		init : function(){
			$('h1.title').text(sessionStorage.getItem('restaurante'));
			$('h2.title').text(App.week(sessionStorage.getItem('dia')));
			App.Cardapio.getList();
			$.each(App.Cardapio.list, function (i,v){
				var html  = '<ul><li><b>'+v.nome+'</b></li><li>'+v.descricao+'</li></ul>';
				html += '<div class="picture"><img src="'+App.imgs+v.imagem0+'" /><button id="avaliar" data-idpratos="'+v.idpratos+'">Avaliar</button></div>';
				$('.container').append(html);
				App.Avaliacoes.appendList(v.idpratos);
				App.Avaliacoes.modal();
			});
		},
		getList : function(){
			$.ajax({
                type: 'POST',
                url: App.url ,
                data: { acao: 'listar', pagina: 'pratos', parametros: [sessionStorage.getItem('idrestaurante'), sessionStorage.getItem('dia')] },
                success: function(response){
                	App.Cardapio.list = response;
                },
                dataType: 'json',
                async: false
            });
		}
	},
	Restaurantes : {
		list : null,
		getList : function(){
			$.ajax({
                type: 'POST',
                url: App.url ,
                data: { acao: 'listar', pagina: 'restaurantes' },
                success: function(response){
                	App.Restaurantes.list = response;
                },
                dataType: 'json',
                async: false
            });
		}
	},
	Usuarios: {
		client : sessionStorage.getItem('client') != undefined ? JSON.parse(sessionStorage.getItem('client')) : null,
		getClient: function(key){
			$.ajax({
                type: 'POST',
                url: App.url ,
                data: { acao: 'permitir', pagina: 'usuarios', parametros: [{'chave' : key}] },
                success: function(response){
                	if('login' in response){
                		App.Usuarios.client = response;	
                		sessionStorage.setItem('client', JSON.stringify(response));
                	}
                },
                dataType: 'json',
                async: false
            });
		},
		auth: function(){			
			App.Usuarios.getClient($('.password').val());			
			if(App.Usuarios.client != null){
				sessionStorage.setItem('chave', $('.password').val() );
				$('.modal, .mask').fadeOut();
			}else{
				/*
				window.plugins.toast.showShortBottom('Você não é cadastrado para inserir comentários.');
				navigator.notification.vibrate(100);	
				*/								
			}
		}
	}
}
$(document).ready(function(){
	if(sessionStorage.getItem('page') == undefined){
		sessionStorage.setItem('page', 'Home');
	}
	App.rate();
	eval('App.'+sessionStorage.getItem('page')+'.init();');	
	//screen.lockOrientation('portrait');
});
document.addEventListener("backbutton", backKeyDown, true);
function backKeyDown() {
 	sessionStorage.setItem('page', 'Home');
 	window.location = 'index.html';
}